
/*
 * 文件名：WebSocketTest.java
 * 版权：Copyright by www.rsrtech.net
 * 描述：
 * 修改人：郑净云
 * 修改时间：2018年8月1日
 */

package com.snailhd.websocket;

import com.snailhd.common.entity.BaseFuture;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;

/**
 * ServerEndpoint 注解是一个类层次的注解，它的功能主要是将目前的类定义成一个websocket服务器端,
 * 注解的值将被用于监听用户连接的终端访问URL地址,客户端可以通过这个URL来连接到WebSocket服务器端
 * ServerEndpoint 可以把当前类变成websocket服务类
 *
 * @author snailhd
 */
@Slf4j
@ServerEndpoint("/websocket/{token}")
@Component
@Getter
public class WebSocketHandler {
    
    public static ConcurrentHashMap<String, Session> SESSIONS = new ConcurrentHashMap<>();

    @OnOpen
    public void onOpen(@PathParam(value = "token") String token, Session session,EndpointConfig endpointConfig) {
        log.info("用户："+token +"连接上");
        SESSIONS.put(token,session);
        log.info("当前连接数：{}",SESSIONS.size());
    }

    @OnClose
    public boolean onClose(@PathParam(value = "token") String token,Session session,CloseReason closeReason) {
        SESSIONS.remove(token);
        log.info("关闭一个用户链接{}",token);
        return true;
    }

    @OnMessage
    public void onMessage(@PathParam(value = "token") String token,String message,Session session) {
        log.info("来自客户端："+token+"的消息:" + message);

    }

    @OnError
    public void onError(@PathParam(value = "token") String token,Session session, Throwable error) {
        log.error("连接异常：",error);
    }

    public static boolean sendMsg(String userid, String msg) {
        Session session = SESSIONS.get(userid);
        BaseFuture future = null;
        if(session!=null){
            if(session.isOpen()){
                session.getAsyncRemote().sendText(msg);
                return true;
            }else{
                log.debug("客户端已断开：{}",userid);
                try {
                    session.close();
                } catch (IOException e) {
                    log.error("关闭session 异常",e);
                }
            }
        }else{
            log.debug("客户端未连接：{}",userid);
        }
        return false;
    }



}
